<template>
    <div class="app-container">
        <el-form :inline="true" :model="queryParams" class="demo-form-inline">
            <el-form-item label="角色名字">
                <el-input size="mini" v-model="queryParams.roleName" placeholder="角色名字"></el-input>
            </el-form-item>
            <el-form-item label="角色key">
                <el-input size="mini" v-model="queryParams.roleKey" placeholder="角色key"></el-input>
            </el-form-item>
            <el-form-item label="角色状态">
                <el-select size="mini" v-model="queryParams.status" placeholder="角色状态">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="禁用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button size="mini" type="primary" @click="handleQuery">查询</el-button>
                <el-button size="mini"  @click="handleResetQuery">重置</el-button>
            </el-form-item>
        </el-form>
    <el-row :gutter="5">
        <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini">添加</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button icon="el-icon-delete" type="danger" @click="handleDelete" size="mini">删除选中</el-button>
        </el-col>
    </el-row>
    <el-table
            :data="tableData"
            stripe
            border
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :cell-style="{padding:'3px'}"
    >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="roleId" label="角色ID"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleKey" label="角色KEY"></el-table-column>
        <el-table-column prop="roleSort" label="显示顺序"></el-table-column>
        <el-table-column prop="dataScope" label="数据权限"></el-table-column>
        <el-table-column label="角色状态">
            <template slot-scope="scope">
                <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                ></el-switch>
            </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="160">
            <template slot-scope="scope">
                <el-tooltip content="授权" placement="right">
                    <el-button @click="handleAuth(scope.row)" type="primary" size="small" icon="el-icon-s-tools" circle></el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="right">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small" icon="el-icon-edit" circle></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="right">
                    <el-button @click="handleDeleteRow(scope.row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
                </el-tooltip>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            layout="total, prev, pager, next"
            v-show="total>0"
            :total="total"
            :page-size="queryParams.limit"
            @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="form.roleName" placeholder="请输入角色名称" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="角色KEY" prop="roleKey">
                        <el-input v-model="form.roleKey" placeholder="请输入角色KEY" maxlength="20"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="显示顺序" prop="roleSort">
                        <el-input v-model="form.roleSort" placeholder="请输入显示顺序" maxlength="20"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="数据权限" prop="dataScope">
                        <el-input v-model="form.dataScope" placeholder="请数据权限" maxlength="30" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>

        <!-- 添加或修改授权对话框 -->
        <el-dialog :title="title" :visible.sync="openAuth" width="600px" append-to-body>
            <el-tree
                    ref="menus"
                    :props="defaultProps"
                    :data="menus"
                    :check-strictly="true"
                    node-key="id"
                    show-checkbox
                    :default-checked-keys="checkedKeys"
                    @node-click="onMenuNodeClick"
            ></el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitAuthForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    import {list,del,get,add,update,menuTree,roleMenus,auth} from "@/api/system/role";
    export default {
        name: "Role",
        data() {
            return {
                // 授权功能声明的变量
                roleName: '',
                menus: [],
                checkedKeys:[],
                defaultProps: {
                    children: "children",
                    label: "title",
                    id: "id"
                },
                // 角色功能声明的变量
                queryParams: { page: 1, limit: 2 },
                total: 0,
                tableData: [],
                multipleSelection: [],
                title: '',
                // 添加/修改表单参数
                form: {
                },
                // 添加/修改表单校验
                rules: {
                    roleName: [
                        {required: true, message: "角色名称不能为空", trigger: "blur"}
                    ],
                    roleKey: [
                        {required: true, message: "角色KEY不能为空", trigger: "blur"}
                    ],
                    roleSort: [
                        {required: true, message: "显示顺序不能为空", trigger: "blur"}
                    ],
                    dataScope: [
                        {required: true, message: "数据权限不能为空", trigger: "blur"},
                    ]
                },
                // 是否显示弹出层
                open: false,
                openAuth: false
            }
        },
        created() {
            this.getList()
        },
        watch: {
            // 删除最后一页所有数据时，回到上一页
            total(val) {
                if(val == (this.queryParams.page-1) * this.queryParams.limit){
                    this.queryParams.page--
                    this.getList()
                }
            }
        },
        methods: {
            handleQuery() {
                this.getList()
            },
            handleResetQuery() {
               this.queryParams = {
                   limit: 2,
                   page: 1,
                   roleName: undefined,
                   roleKey: undefined,
                   status: undefined
               }
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.openAuth = false;
                this.reset();
            },
            reset() {
                this.form = {
                    roleId: undefined,
                    roleName: undefined,
                    roleKey: undefined,
                    roleSort: undefined,
                    dataScope: undefined,
                    status: undefined,
                }
                this.checkedKeys = []
                this.roleName = ''
            },
            submitAuthForm() {
                let checkedKeys = this.$refs.menus.getCheckedKeys();
                auth({roleName: this.roleName, checkedMenuIds: checkedKeys.join(",")}).then(resp=>{
                    if (resp.code == 200) {
                        this.$message({message:'授权成功', type:'success'})
                    } else {
                        this.$message({message:'授权失败:' + resp.msg, type:'success'})
                    }
                    this.reset()
                    this.openAuth = false
                })
            },
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if(valid) {
                        if(this.form.roleId != undefined) {
                            update(this.form).then(()=>{
                                this.$message({message:'修改成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        } else {
                            this.form.status = 0;
                            add(this.form).then(()=>{
                                this.$message({message:'添加成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        }
                    }
                })
            },
            getList() {
                list(this.queryParams).then(response => {
                    this.tableData = response.data.records
                    this.total = response.data.total
                })
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
                console.log(this.multipleSelection);
            },
            handleCurrentChange(val) {
                this.queryParams.page = val;
                this.getList()
            },
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加角色";
            },
            handleView(row) {
                get(row.roleId).then(resp=>{
                    console.log(resp);
                })
            },
            handleAuth(row) {
                menuTree().then(resp=>{
                    this.menus = resp.data;
                    this.roleName = row.roleName;
                    roleMenus(row.roleName).then(res=>{
                        this.checkedKeys = res.data;
                    })
                    this.openAuth = true;
                })
            },
            handleEdit(row) {
                this.reset();
                get(row.roleId).then(resp=>{
                    this.form = resp.data;
                    this.open = true;
                    this.title = "修改角色";
                })
            },
            handleDeleteRow(row) {
                this.$confirm('确定删除"' + row.roleName + '"吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let idList = row.roleId;
                    del(idList).then(resp => {
                        this.$message({
                            type: 'success',
                            message: resp.msg
                        });
                        this.getList()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleDelete() {
                if(this.multipleSelection.length == 0) {
                    this.$alert('请至少选中一条记录')
                } else {
                    this.$confirm('确定删除选中的记录吗, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let idList = this.multipleSelection.map(row=>row.roleId).join(",");
                        del(idList).then(resp => {
                            this.$message({
                                type: 'success',
                                message: resp.msg
                            });
                            this.getList()
                        })

                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            handleStatusChange(row) {
                let text = row.status === "0" ? "启用" : "停用";
                this.$confirm('确认要"' + text + '""' + row.roleName + '"部门吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return update({roleId:row.roleId, status:row.status});
                }).then(() => {
                    this.$message(text + "成功");
                }).catch(function() {
                    row.status = row.status === "0" ? "1" : "0";
                });
            },
            onMenuNodeClick(data) {
                console.log(data);
            }
        }

    }
</script>
